<template>
  <div id="captcha-container">
    <img :src="bgImage" id="captcha-img" />
    <div
      id="slider"
      :style="{ left: sliderPosition + 'px' }"
      @mousedown="onMouseDown"
    >
      拖动我
    </div>
    <div id="message">{{ message }}</div>
  </div>
</template>

<script setup>
  import { ref } from 'vue'

  const bgImage = ref('http://localhost:8001/puzzle') // 替换为你的图片 API
  const sliderPosition = ref(0)
  const message = ref('请拖动拼图验证')

  const onMouseDown = (event) => {
    document.onmousemove = onMouseMove
    document.onmouseup = onMouseUp
  }

  const onMouseMove = (event) => {
    const container = document.getElementById('captcha-container')
    let newLeft = event.clientX - container.getBoundingClientRect().left - 50 // 50 是 slider 的宽度的一半

    // 限制 slider 的移动范围
    if (newLeft < 0) newLeft = 0
    if (newLeft > (container.offsetWidth - 100)) newLeft = container.offsetWidth - 100

    sliderPosition.value = newLeft
  }

  const onMouseUp = () => {
    document.onmousemove = null
    document.onmouseup = null

    const container = document.getElementById('captcha-container')
    if (sliderPosition.value >= container.offsetWidth - 100) {
      message.value = '验证成功！'
    // 成功后可进行后续操作，例如重置验证码或跳转
    } else {
      message.value = '请拖动拼图到正确的位置！'
      resetSlider()
    }
  }

  const resetSlider = () => {
    sliderPosition.value = 0 // 重置 slider 位置
  }
</script>

<style scoped>
  #captcha-container {
    position: relative;
    width: 300px; /* 图片宽度 */
    height: 150px; /* 图片高度 */
    overflow: hidden;
    border: 1px solid #ccc;
    margin: 20px auto; /* 中央对齐 */
  }

  #captcha-img {
    width: 100%;
    height: auto;
  }

  #slider {
    position: absolute;
    width: 100px; /* 拖动条的宽度 */
    height: 40px; /* 拖动条的高度 */
    background-color: #007bff;
    color: white;
    text-align: center;
    line-height: 40px; /* 使字体垂直居中 */
    cursor: pointer;
  }

  #message {
    margin-top: 10px;
    font-size: 16px;
    color: red;
  }
</style>
